package Heap;

public class _313_SuperUglyNumber {
    public int nthSuperUglyNumber(int n, int[] primes) {
        int[] ugly = new int[n];
        ugly[0] = 1;
        int[] product = new int[primes.length];
        int[] index = new int[primes.length];
        for (int i = 0; i < product.length; i++) {
            product[i] = primes[i];
        }
        for (int i = 1; i < n; i++) {
            int min = Integer.MAX_VALUE;
            for (int value : product) {
                min = Math.min(value, min);
            }
            ugly[i] = min;
            for (int j = 0; j < product.length; j++) {
                if (product[j] == min) {
                    product[j] = primes[j] * ugly[++index[j]];
                }
            }
        }
        return ugly[n - 1];
    }
}
